package com.example.categoryservice.service.impl;

import com.example.categoryservice.mapper.CategoryMapper;
import com.example.categoryservice.service.CategoryService;
import com.example.pojo.dto.CategoryGroupDTO;
import com.example.pojo.dto.CategoryInsertDTO;
import com.example.pojo.dto.CategoryPageQueryDTO;
import com.example.pojo.entity.Category;
import com.example.pojo.entity.result.PageResult;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
@RequiredArgsConstructor
public class CategoryServiceImpl implements CategoryService {
    private final CategoryMapper categoryMapper;

    /**
     * 分页查询图书对象
     *
     * @param categoryPageQueryDTO
     * @return
     */
    @Override
    public PageResult<Category> list(CategoryPageQueryDTO categoryPageQueryDTO) {
        //设置分页条件
        PageHelper.startPage(categoryPageQueryDTO.getPage(), categoryPageQueryDTO.getPageSize());

        //执行查询
        List<Category> catList = categoryMapper.listByQuery(categoryPageQueryDTO);

        Page<Category> page = (Page<Category>) catList;

        //返回分页结果
        return new PageResult<>(page.getTotal(), catList);
    }

    /**
     * 新增图书分类
     *
     * @param categoryInsertDTO
     */
    @Override
    public Long insertCategory(CategoryInsertDTO categoryInsertDTO) {
        //查询图书分类是否已经存在
        CategoryGroupDTO categoryGroupDTO = CategoryGroupDTO.builder()
                .bookName(categoryInsertDTO.getBookName())
                .author(categoryInsertDTO.getAuthor())
                .publishingHouse(categoryInsertDTO.getPublishingHouse())
                .build();

        Category category = categoryMapper.selectByGroup(categoryGroupDTO);

        if (category == null) {
            //插入图书分类a
            categoryInsertDTO.setRepertory(1);
            categoryInsertDTO.setUpdateTime(LocalDateTime.now());

            categoryMapper.insertCategory(categoryInsertDTO);
            return categoryInsertDTO.getCategoryId();
        } else {
            Long categoryId = category.getId();
            categoryMapper.plusRepertory(categoryId);
            return categoryId;
        }
    }

    /**
     * 减少图书分类的库存
     *
     * @param id
     */
    @Override
    public void decrease(Long id) {
        categoryMapper.decrease(id);
    }

    /**
     * 增加图书分类的库存
     *
     * @param id
     */
    @Override
    public void plus(Long id) {
        categoryMapper.plus(id);
    }
}
